package com.soriya.nestlive.repository

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.soriya.nestlive.model.Category
import com.soriya.nestlive.net.CategoryApi
import javax.inject.Inject

class CategoryPagingRepository @Inject constructor(
    private val categoryApi: CategoryApi
) : PagingSource<Int, Category>() {
    override fun getRefreshKey(state: PagingState<Int, Category>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Category> {
        val next = params.key ?: 1

        val pageSize = 5

        return try {
            val categoryList = categoryApi.categoryList(next, pageSize)

            LoadResult.Page(
                data = categoryList.data.list,
                prevKey = null,
                nextKey = if (categoryList.data.totalPage > categoryList.data.currentPage) categoryList.data.currentPage + 1 else null
            )
        } catch (e : Exception) {
            LoadResult.Error(e)
        }
    }
}